////
////  TendencyViewController.m
////  Romens.XSBalance
////
////  Created by 李美东 on 16/2/23.
////  Copyright © 2016年 孙博. All rights reserved.
////
//
#import "TendencyViewController.h"
#import "HealthModel.h"
#import "ChartModel.h"
#import "PopoverView.h"
#import "PopViewCell.h"
#import "TendencyCell.h"
#import "WebRequestData.h"
#import "ToolHelper.h"
#import "DataDBManager.h"
#import "RuntimeStatus.h"

@interface TendencyViewController ()<UITableViewDataSource,UITableViewDelegate,PopoverViewDelegate>
{
    //总图表数组
    NSMutableArray *chartArray;
   
    //需要显示的表图数组
    NSMutableArray *chartDisplayArray;
    
    //图标X轴需要显示的数据；
    NSMutableArray* xVals;
    
    DataDBManager * manager;

}
@property(nonatomic, strong) UITableView *chartTableView;
@property(nonatomic, strong) UIButton *edit;
@property(nonatomic, strong) PopoverView *pv;
@property(nonatomic, assign) CGPoint point;
@property(nonatomic, strong) UITableView *popTableView;
@property(nonatomic, strong) UITapGestureRecognizer *recognizerTap;
@property(nonatomic, strong) UIBarButtonItem *rightButton;
@property (nonatomic,strong) UISegmentedControl *segmentChart;

@end

@implementation TendencyViewController



- (void)viewDidLoad {
    [super viewDidLoad];
    
    _rightButton = [[UIBarButtonItem alloc] initWithTitle:@"编辑" style:(UIBarButtonItemStylePlain)target:self action:@selector(PopView)];
    self.navigationItem.rightBarButtonItem = _rightButton;
    
    [self InitReportData];
    manager=[[DataDBManager alloc]init];
    
    [self InitUI];
    [self GetUserTodayChartData];
    //通知，当前用户改变；
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(currentUserChangeNotification:) name:@"CurrentUserChange" object:nil];
}
-(void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}
- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self InitReportData];
    [self GetUserTodayChartData];
}
# pragma mark -当前用户改变；
-(void)currentUserChangeNotification:(NSNotification*)notify
{
    [self InitReportData];
    [self GetUserTodayChartData];
}

/**
 *  初始化图表数据
 */
-(void)InitReportData
{
    chartArray =[[NSMutableArray alloc] init];
    chartDisplayArray=[[NSMutableArray alloc] init];
    
    HealthModel *model=[[HealthModel alloc] init];
    model.Name=@"体重";
    model.ImageName=@"weight";
    model.KEY=@"WEIGHT";
    model.IsSHow=YES;
    [chartArray addObject:model];
    [chartDisplayArray addObject:model];
    
    model=[[HealthModel alloc] init];
    model.Name=@"BMI";
    model.ImageName=@"BMI";
    model.KEY=@"BMI";
    model.IsSHow=NO;
    [chartArray addObject:model];

    model=[[HealthModel alloc] init];
    model.Name=@"脂肪率";
    model.ImageName=@"脂肪率";
    model.KEY=@"FAT";
    model.IsSHow=NO;
    [chartArray addObject:model];
    
    model=[[HealthModel alloc] init];
    model.Name=@"骨骼值";
    model.ImageName=@"bones";
    model.KEY=@"BONES";
    model.IsSHow=NO;
    [chartArray addObject:model];

    model=[[HealthModel alloc] init];
    model.Name=@"水分值";
    model.ImageName=@"水分值";
    model.KEY=@"WATER";
    model.IsSHow=NO;
    [chartArray addObject:model];

    model=[[HealthModel alloc] init];
    model.Name=@"肌肉值";
    model.ImageName=@"muscle";
    model.KEY=@"MUSCLE";
    model.IsSHow=NO;
    [chartArray addObject:model];

    model=[[HealthModel alloc] init];
    model.Name=@"卡路里";
    model.ImageName=@"calorie";
    model.KEY=@"CALORIE";
    model.IsSHow=NO;
    [chartArray addObject:model];
    
    
    xVals=[[NSMutableArray alloc]init];
    NSDate *nowDate = [NSDate date];
    NSDate *theDate;
    NSTimeInterval  oneDay = 24*60*60*1;  //1天的长度
    NSCalendar *calendar = [NSCalendar currentCalendar];
    NSUInteger unitFlags = NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit;
    for (int i = 6; i>= 0;i--)
    {
        theDate = [nowDate initWithTimeIntervalSinceNow: -oneDay*i];
        NSDateComponents *dateComponent = [calendar components:unitFlags fromDate:theDate];
        int day =(int)[dateComponent day];
        [xVals addObject:[NSString stringWithFormat:@"%i",day]];
    }
}

-(void)InitUI{
    UIView *segView = [[UIView alloc]init];
    [self.view addSubview:segView];
    segView.translatesAutoresizingMaskIntoConstraints = NO;
    NSMutableArray *segmentedArray = [[NSMutableArray alloc]initWithObjects: @"周", @"月", @"年",nil];
    _segmentChart = [[UISegmentedControl alloc]initWithItems:segmentedArray];
    _segmentChart.segmentedControlStyle = UISegmentedControlStylePlain;
    _segmentChart.selectedSegmentIndex = 0;
    _segmentChart.tintColor = SystemColor;
    _segmentChart.translatesAutoresizingMaskIntoConstraints = NO;
    [_segmentChart addTarget:self action:@selector(SegmentedSelectTime:) forControlEvents:UIControlEventValueChanged];
    [segView addSubview:_segmentChart];

    _chartTableView = [[UITableView alloc]initWithFrame:CGRectZero style:UITableViewStyleGrouped];
    _chartTableView.translatesAutoresizingMaskIntoConstraints = NO;
    _chartTableView.delegate = self;
    _chartTableView.dataSource = self;
    [self.view addSubview:_chartTableView];
    _chartTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    
    [self.view addConstraints:[ToolHelper GetNSLayoutCont:NSDictionaryOfVariableBindings(segView) format:@"H:|[segView]|"]];
    [self.view addConstraints:[ToolHelper GetNSLayoutCont:NSDictionaryOfVariableBindings(_chartTableView) format:@"H:|[_chartTableView]|"]];
    [self.view addConstraints:[ToolHelper GetNSLayoutCont:NSDictionaryOfVariableBindings(segView,_chartTableView) format:@"V:|[segView(==45)][_chartTableView]|"]];
    
    [segView addConstraints:[ToolHelper GetNSLayoutCont:NSDictionaryOfVariableBindings(_segmentChart) format:@"H:|-[_segmentChart]-|"]];
    [segView addConstraints:[ToolHelper GetNSLayoutCont:NSDictionaryOfVariableBindings(_segmentChart) format:@"V:|-10-[_segmentChart]-|"]];
    
}

-(void)PopView{

    UIView *popBackView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 220, SCREEN_HEIGHT/2)];
    
    _popTableView = [[UITableView alloc] init];
    _popTableView.delegate = self;
    _popTableView.dataSource = self;
    _popTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    [_popTableView setEditing:YES animated:YES];
    [popBackView addSubview:_popTableView];
    _popTableView.translatesAutoresizingMaskIntoConstraints = NO;
    
    _pv = [PopoverView showPopoverAtPoint:CGPointMake(SCREEN_HEIGHT-20, -5)
                                   inView:self.view
                          withContentView:popBackView
                                 delegate:self];
    
    UIView *popFooterView = [[UIView alloc]init];
    popFooterView.translatesAutoresizingMaskIntoConstraints = NO;
    popFooterView.backgroundColor = SystemColor;
    [popBackView addSubview:popFooterView];
    
    UIButton *sureButton = [UIButton buttonWithType:UIButtonTypeSystem];
    sureButton.translatesAutoresizingMaskIntoConstraints = NO;
    [popFooterView addSubview:sureButton];
    [sureButton setTitle:@"确定" forState:UIControlStateNormal];
    [sureButton addTarget:self action:@selector(sureChange) forControlEvents:UIControlEventTouchUpInside];
    [sureButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [sureButton setTitleColor:[UIColor lightGrayColor] forState:UIControlStateSelected];

    
    [popBackView addConstraints:[ToolHelper GetNSLayoutCont:NSDictionaryOfVariableBindings(_popTableView) format:@"H:|[_popTableView]|"]];
    [popBackView addConstraints:[ToolHelper GetNSLayoutCont:NSDictionaryOfVariableBindings(popFooterView) format:@"H:|[popFooterView]|"]];
    
    [popBackView addConstraints:[ToolHelper GetNSLayoutCont:NSDictionaryOfVariableBindings(_popTableView,popFooterView) format:@"V:|[_popTableView][popFooterView(40)]|"]];
    
    [popFooterView addConstraints:[ToolHelper GetNSLayoutCont:NSDictionaryOfVariableBindings(sureButton) format:@"H:|[sureButton]|"]];
    [popFooterView addConstraints:[ToolHelper GetNSLayoutCont:NSDictionaryOfVariableBindings(sureButton) format:@"V:|[sureButton]|"]];

}

#pragma mark 获取网络数据
-(void)GetUserTodayChartData{
    for (HealthModel * model in chartArray)
    {
        [manager GetUserTestData:[RuntimeStatus instance].CurrUser.USERID startdate: @"2016-03-18" endDate:@"2016-03-21" key:model.KEY suessblock:^(id array)
         {
             
             NSMutableArray * array1=(NSMutableArray *)array;
             for (NSMutableDictionary * resultDic in array1)
             {
                 if (!model.XArray) {
                     model.XArray=[NSMutableArray arrayWithObjects:[resultDic objectForKey:@"CREATED"],nil];
                 }
                 else
                 {
                     [model.XArray addObject:[resultDic objectForKey:@"CREATED"]];
                 }
                 if (!model.YArray) {
                     model.YArray=[NSMutableArray arrayWithObjects:[resultDic objectForKey:@"VALUE"],nil];
                 }
                 else
                 {
                     [model.YArray addObject:[resultDic objectForKey:@"VALUE"]];
                 }
             }
             [_chartTableView reloadData];
         }];
     }
}
#pragma mark 线性图数据
-(ChartData *)LineChartData:(NSUInteger)index{
    NSMutableArray *yVals=[[NSMutableArray alloc]init];
    HealthModel * model =[chartDisplayArray objectAtIndex:index];
    if (model.XArray.count!=0) {
            for (int i = 0; i < xVals.count; i++) {
                double yData=0;
                if (i== xVals.count-1) {
                      yData=[[model.YArray objectAtIndex:0] doubleValue];
                }
            [yVals addObject:[[BarChartDataEntry alloc] initWithValue:yData xIndex:i]];
        }
    }
    LineChartDataSet *set1 = [[LineChartDataSet alloc] initWithYVals:yVals label:model.Name];
//    set1.lineDashLengths = @[@5.f, @2.5f];
//    set1.highlightLineDashLengths = @[@5.f, @2.5f];
    [set1 setColor:SystemColor];
    [set1 setCircleColor:UIColor.blackColor];
    set1.lineWidth = 1.0;
    set1.circleRadius = 2.0;
    set1.drawCircleHoleEnabled = NO;
    set1.valueFont = [UIFont systemFontOfSize:9.f];
    set1.fillAlpha = 65/255.0;
    set1.fillColor = UIColor.blackColor;
    
    NSMutableArray *dataSets = [[NSMutableArray alloc] init];
    [dataSets addObject:set1];
    
  LineChartData *  data = [[LineChartData alloc] initWithXVals:xVals dataSets:dataSets];
    return data;
}
#pragma mark 编辑
-(void)EditChart{
    CGPoint point = _edit.center;
    _point = CGPointMake(point.x,point.y+15);
    
    UIView *popBackView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 220, SCREEN_HEIGHT/2)];
    
    _popTableView = [[UITableView alloc] init];
    _popTableView.delegate = self;
    _popTableView.dataSource = self;
    _popTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    [_popTableView setEditing:YES animated:YES];
    [popBackView addSubview:_popTableView];
    _popTableView.translatesAutoresizingMaskIntoConstraints = NO;
    
    _pv = [PopoverView showPopoverAtPoint:_point
                                   inView:self.view
                          withContentView:popBackView
                                 delegate:self];
    
    UIView *popFooterView = [[UIView alloc]init];
    popFooterView.translatesAutoresizingMaskIntoConstraints = NO;
    popFooterView.backgroundColor = SystemColor;
    [popBackView addSubview:popFooterView];
    
    UIButton *sureButton = [[UIButton alloc]init];
    sureButton.translatesAutoresizingMaskIntoConstraints = NO;
    [popFooterView addSubview:sureButton];
    [sureButton setTitle:@"确定" forState:UIControlStateNormal];
    [sureButton addTarget:self action:@selector(sureChange) forControlEvents:UIControlEventTouchUpInside];
    
    
    [popBackView addConstraints:[ToolHelper GetNSLayoutCont:NSDictionaryOfVariableBindings(_popTableView) format:@"H:|[_popTableView]|"]];
    [popBackView addConstraints:[ToolHelper GetNSLayoutCont:NSDictionaryOfVariableBindings(popFooterView) format:@"H:|[popFooterView]|"]];
    
    [popBackView addConstraints:[ToolHelper GetNSLayoutCont:NSDictionaryOfVariableBindings(_popTableView,popFooterView) format:@"V:|[_popTableView][popFooterView(40)]|"]];
    
    [popFooterView addConstraints:[ToolHelper GetNSLayoutCont:NSDictionaryOfVariableBindings(sureButton) format:@"H:|[sureButton]|"]];
    [popFooterView addConstraints:[ToolHelper GetNSLayoutCont:NSDictionaryOfVariableBindings(sureButton) format:@"V:|[sureButton]|"]];
    
}

-(void)SegmentedSelectTime:(UISegmentedControl *)sender
{
//    
    if (xVals.count!=0) {
        [xVals removeAllObjects];
    }
    NSDate *nowDate = [NSDate date];
    NSDate *theDate;
    NSTimeInterval  oneDay = 24*60*60*1;  //1天的长度
    NSCalendar *calendar = [NSCalendar currentCalendar];
    NSUInteger unitFlags = NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit;
    switch (sender.selectedSegmentIndex)
    {
        
        case 0:
        {
            for (int i = 6; i>= 0;i--)
            {
                theDate = [nowDate initWithTimeIntervalSinceNow: -oneDay*i];
                NSDateComponents *dateComponent = [calendar components:unitFlags fromDate:theDate];
                int day =(int)[dateComponent day];
                [xVals addObject:[NSString stringWithFormat:@"%i",day]];
            }
            
        }
            break;
        case 1:
        {
            for (int i = 30; i >=0; i--)
            {
                theDate = [nowDate initWithTimeIntervalSinceNow: -oneDay*i];
                NSDateComponents *dateComponent = [calendar components:unitFlags fromDate:theDate];
                int day =(int)[dateComponent day];
                [xVals addObject:[NSString stringWithFormat:@"%i",day]];
                
            }
            
        }
            break;
        case 2:
        {
            NSDateComponents *dateComponent = [calendar components:unitFlags fromDate:nowDate];
            int day =(int)[dateComponent month];
            for (int i =11; i >=0; i--)
            {
                int theMonth=(day-i+12)%12;
                if (theMonth==0)
                {
                    theMonth=12;
                }
                [xVals addObject:[NSString stringWithFormat:@"%i",theMonth]];
            }
            
        }
            break;
    }
    [_chartTableView reloadData];
}


#pragma mark 确定按钮
-(void)sureChange{
    [chartDisplayArray removeAllObjects];
    for (HealthModel*model in chartArray) {
        if(model.IsSHow)
        {
            [chartDisplayArray addObject:model];
        }
    }
    [_pv dismiss:YES];
    [_chartTableView reloadData];
}


//点击是否显示列
- (void)TapIsNotDisplayChart:(UITapGestureRecognizer *)sender {
    
    UIView *v = sender.view.superview;
    PopViewCell *cell = (PopViewCell *)v;//获取cell
    NSIndexPath *indexPath = [_popTableView indexPathForCell:cell];
    HealthModel*model=[chartArray objectAtIndex:indexPath.row];
    model.IsSHow=!model.IsSHow;
    [_popTableView reloadData];
}


#pragma mark tableview Delegate
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if(tableView ==_chartTableView)
    {
       return chartDisplayArray.count;
    }
    else
    {
        return chartArray.count;
    }
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    if (tableView == _chartTableView) {
        static NSString *CellIdentifier = @"ChartTableCell";
        TendencyCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
        if (cell == nil) {
            cell = [[TendencyCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
        }
        cell.selectionStyle=UITableViewCellSelectionStyleNone;
        HealthModel * model=[chartDisplayArray objectAtIndex:indexPath.row];
        cell.reportName.text=model.Name;
        cell.reportIcon.image = [UIImage imageNamed:model.ImageName];
        [cell.linechartView clearValues];
        cell.linechartView.data = [self LineChartData:indexPath.row];
       return cell;
    }
    else{
        
        static NSString *CellIdentifier = @"PopTableCell";
        PopViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
        if (cell == nil) {
            cell = [[PopViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
        }
            HealthModel*model=[chartArray objectAtIndex:indexPath.row];
            cell.chartName.text =model.Name;
            
            if (model.IsSHow) {
                cell.checkIcon.image = [UIImage imageNamed:@"select"];
            }else{
                cell.checkIcon.image = [UIImage imageNamed:@"unselect"];
            }
            
            
            _recognizerTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(TapIsNotDisplayChart:)];
            [cell.contentView addGestureRecognizer:_recognizerTap];
        return cell;
    }
    
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    if (tableView == _chartTableView)
    {
        return 270;
    }
    else
    {
        return 44;
    }
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return CGFLOAT_MIN;
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return CGFLOAT_MIN;
} 



#pragma mark 决定tableview的编辑模式
- (UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath {
    return UITableViewCellEditingStyleNone;
}

//上下移动cell
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath
{
    id name = [chartArray objectAtIndex:fromIndexPath.row];
    [chartArray removeObjectAtIndex:fromIndexPath.row];
    [chartArray insertObject:name atIndex:toIndexPath.row];
    
}

- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (tableView == _chartTableView)
    {
        return false;
    }
    else
    {
        return true;
    }
}
@end
